// pages/coupon-form/coupon-form.ts
import { MerchantAPI } from '../../utils/api'

Page({
  data: {
    bindingId: '',
    isEdit: false,
    formData: {
      couponId: '',
      scope: 1,
      status: 1
    },
    scopeOptions: [
      { value: 1, label: '全场通用' },
      { value: 2, label: '指定商品' },
      { value: 3, label: '指定分类' }
    ],
    statusOptions: [
      { value: 1, label: '启用' },
      { value: 0, label: '禁用' }
    ]
  },

  onLoad(options: any) {
    if (options.bindingId) {
      this.setData({
        bindingId: options.bindingId,
        isEdit: true
      });
      this.loadCouponDetail(options.bindingId);
    }
  },

  async loadCouponDetail(bindingId: string) {
    try {
      wx.showLoading({ title: '加载中...' });
      const response = await MerchantAPI.getCouponDetail(bindingId);

      if (response && response.code === 200 && response.data) {
        this.setData({
          formData: {
            couponId: response.data.couponId || '',
            scope: response.data.scope || 1,
            status: response.data.status || 1
          }
        });
      }
    } catch (error) {
      console.error('加载优惠券详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  onCouponIdInput(e: any) {
    this.setData({
      'formData.couponId': e.detail.value
    });
  },

  onScopeChange(e: any) {
    this.setData({
      'formData.scope': parseInt(e.detail.value)
    });
  },

  onStatusChange(e: any) {
    this.setData({
      'formData.status': parseInt(e.detail.value)
    });
  },

  async submitForm() {
    const { formData, isEdit, bindingId } = this.data;

    // 验证
    if (!formData.couponId) {
      wx.showToast({
        title: '请输入优惠券ID',
        icon: 'none'
      });
      return;
    }

    try {
      wx.showLoading({ title: '提交中...' });

      const params: any = {
        couponId: formData.couponId,
        scope: formData.scope,
        status: formData.status
      };

      if (isEdit) {
        params.bindingId = bindingId;
      }

      const response = isEdit
        ? await MerchantAPI.updateCoupon(params)
        : await MerchantAPI.createCoupon(params);

      if (response && response.code === 200) {
        wx.showToast({
          title: isEdit ? '更新成功' : '创建成功',
          icon: 'success'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: response.msg || '操作失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('提交失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  }
});
